/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package multiface.db.mongodb;

import com.mongodb.BasicDBObject;
import com.mongodb.DB;
import com.mongodb.DBCollection;
import com.mongodb.Mongo;
import com.mongodb.MongoException;
import java.lang.reflect.*;
import java.net.UnknownHostException;
import java.util.logging.Level;
import java.util.logging.Logger;

/**
 *
 * @author Diego64
 */
public class MongoManager {

    public static void persist(Object o) throws MongoException, IllegalAccessException, IllegalArgumentException, InvocationTargetException {
        try {
            Mongo mo = new Mongo("localhost", 27017);
            DB db = mo.getDB("kooper");


            Class c = o.getClass();
            System.out.println("Class: " + c.getSimpleName());

            DBCollection collections = db.getCollection(c.getSimpleName().toLowerCase());
            BasicDBObject doc = new BasicDBObject();

            Field[] fields = c.getDeclaredFields();
            System.out.println("Number fields: " + fields.length);

            Method[] mets = c.getDeclaredMethods();

            for (int m = 0; m < mets.length; m++) {
                Method met = mets[m];
                if (met.getName().contains("get")) {
                    //Properties
                    if (met.getReturnType().getCanonicalName().equals("java.lang.Long") || met.getReturnType().getCanonicalName().equals("long")) {
                        Long ret = (Long) met.invoke(o, new Object[0]);
                        System.out.println(met.getName() + ": " + ret);
                        doc.put(met.getName().replaceFirst("get", "").toLowerCase(), ret);
                    }
                    if (met.getReturnType().getCanonicalName().equals("java.lang.String")) {
                        String ret = (String) met.invoke(o, new Object[0]);
                        System.out.println(met.getName() + ": " + ret);
                        doc.put(met.getName().replaceFirst("get", "").toLowerCase(), ret);
                    }
                }
            }
            collections.insert(doc);

        } catch (UnknownHostException ex) {
            Logger.getLogger(MongoManager.class.getName()).log(Level.SEVERE, null, ex);
        }



    }
}
